package org.wlw.web.servlet;

import org.wlw.web.anno.Resource;
import org.wlw.web.models.User;
import org.wlw.web.service.IUserService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/login")
public class LoginServlet extends BaseServlet{
    private IUserService userService;

    @Resource
    public void setUserService(IUserService userService) {
        this.userService = userService;
    }

    public String index(HttpServletRequest request, HttpServletResponse response) {
        User loginUser = (User)request.getSession().getAttribute("loginUser");
        if(loginUser!=null) {
            return getRedirectUrl("/admin/user");
        }
        return "login";
    }

    public String loginAction(HttpServletRequest request, HttpServletResponse response) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = userService.login(username,password);
        request.getSession().setAttribute("loginUser",user);
        return getRedirectUrl("/admin/user");
    }

    public String logout(HttpServletRequest request,HttpServletResponse response) {
        request.getSession().invalidate();//让浏览器的session失效
        return getRedirectUrl("/login");
    }
}
